#pragma once

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "Log.hpp"
//#include "TcpServer.hpp"
#include "Task.hpp"
#include "SingleThreadPool.hpp"
#include "Socket.hpp"

static const uint16_t g_defaultPort = 8080;
class HttpServer
{
private:
    uint16_t _port;
    Sock _listenSock;

public:
    HttpServer(uint16_t port = g_defaultPort)
        : _port(port)
    {
    }

    void Start()
    {
        LOG(INFO, "HttpServer Start!");

        // 忽略SIGPIPE信号 防止客户端断开连接后 服务器还向客户端发送数据 1.无意义 2.服务端崩溃
        signal(SIGPIPE, SIG_IGN);

        // TcpServer *tsvr = TcpServer::getTcpSvrInstance(_port);

        // 创建线程池
        ThreadPool<Task> *threadPool = ThreadPool<Task>::getThreadPoolInstance();
        threadPool->run();

        _listenSock.Socket();
        _listenSock.Bind(_port);
        _listenSock.Listen();
        while (true)
        {
            std::cout<<"HttpServer Start!"<< std::endl;
            std::string clientIp;
            uint16_t clientPort;
            int sockfd = _listenSock.Accept(&clientIp, &clientPort);
            if (sockfd < 0)
                continue;
            LOG(INFO, "accept new connect: [%s:%d], serviceFd: %d", clientIp.c_str(), clientPort, sockfd);

            Task task(sockfd);
            threadPool->PushTask(task);
        }
    }

    ~HttpServer()
    {
    }
};
